package com.sunday.fangdaifu.activity.main;

import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sunday.common.MarqueeView;
import com.sunday.common.base.BaseFragment;
import com.sunday.common.model.ResultDO;
import com.sunday.common.qrcode.CaptureActivity;
import com.sunday.common.utils.PixUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.fangdaifu.R;
import com.sunday.fangdaifu.activity.common.WebViewActivity;
import com.sunday.fangdaifu.activity.task.TaskDetailActivity;
import com.sunday.fangdaifu.activity.task.UnFinishTaskActivity;
import com.sunday.fangdaifu.base.MyApplication;
import com.sunday.fangdaifu.common.Api;
import com.sunday.fangdaifu.common.ApiClient;
import com.sunday.fangdaifu.common.ApiServiceImpl;
import com.sunday.fangdaifu.model.IndexCount;
import com.sunday.fangdaifu.model.IndexTask;
import com.sunday.fangdaifu.model.PieData;
import com.sunday.fangdaifu.model.TaskDetail;
import com.sunday.fangdaifu.utils.SharePerferenceUtils;
import com.sunday.fangdaifu.widgets.HollowPieNewChart;

import java.sql.Array;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * Created by yun_sheng on 2017/6/29.
 */

public class IndexFragment extends BaseFragment implements ApiServiceImpl.HttpResponseInterface {

    @Bind(R.id.item)
    LinearLayout item;
    @Bind(R.id.noSucCount)
    TextView noSucCount;
    @Bind(R.id.finish)
    TextView finish;
    @Bind(R.id.noFinish)
    TextView noFinish;
    @Bind(R.id.scan)
    ImageView scan;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.title_bar)
    RelativeLayout titleBar;
    @Bind(R.id.marquee_view)
    MarqueeView marqueeView;
    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;

    private LinearLayoutManager manager;
    private int[] mColors = {0xff40acff, 0xff2692ff, 0xFF59c2ff};
    HollowPieNewChart pieNewChart;
    private int userId;


    public static IndexFragment newInstance() {
        IndexFragment fragment = new IndexFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_index, container, false);
        ButterKnife.bind(this, rootView);
        pieNewChart = (HollowPieNewChart) rootView.findViewById(R.id.pie_chart);
        return rootView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        userId = MyApplication.getInstance().getMember().getId();
        init();
        refreshLayout.setColorSchemeResources(R.color.material_red, R.color.material_green,
                R.color.material_blue, R.color.material_yellow);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                init();
            }
        });
    }


    @OnClick({R.id.txt_unfinish, R.id.noFinish, R.id.scan, R.id.layout_knowledge, R.id.ly_weather,R.id.layout_feed_back})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.ly_weather:
                String longitude = "", latitude = "";
                MyApplication.getInstance().requestLocation();
                if (MyApplication.getInstance().isLocatioSuc())
                    longitude = SharePerferenceUtils.getIns().getString("longitude", "");
                latitude = SharePerferenceUtils.getIns().getString("latitude", "");
                String url = String.format("http://api.map.baidu.com/telematics/v3/weather?location=%1$s,%2$s&mcode=2coord_type=bd09ll&output=json&ak=6tYzTvGZSOpYB5Oc2YGGOKt8", longitude, latitude);
                Intent intent2 = new Intent(mContext, WebViewActivity.class);
                intent2.putExtra("url", url);
                intent2.putExtra("title", "天气");
                startActivity(intent2);
                break;
            case R.id.txt_unfinish:
            case R.id.noFinish:
                Intent intent1 = new Intent(mContext, UnFinishTaskActivity.class);
                startActivity(intent1);
                break;
            case R.id.scan:
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.layout_knowledge:
                ((MainActivity) getActivity()).gotoKnowledgePage();
                break;
            case R.id.layout_feed_back:
                ((MainActivity) getActivity()).gotoFeedBack();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        Gson gson = new Gson();
        String result = data.getStringExtra("result");
        if (!TextUtils.isEmpty(result) && result.length() > 4) {
            String id = result. substring(result.lastIndexOf('/') + 1,result.length());
            ApiClient.getApiService().taskId(userId, Integer.valueOf(id), this, new TypeToken<ResultDO<Integer>>() {
            }.getType());
        }

    }

    private void init() {
        showLoadingDialog();
        ApiClient.getApiService().indexTask(userId, this, new TypeToken<ResultDO<List<IndexTask>>>() {
        }.getType());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private List<PieData> datas = new ArrayList<>();

    @Override
    public void onResponce(String key, Object result) {
        if (isFinish) {
            return;
        }
        switch (key) {
            case Api.INDEX_TASK:
                ApiClient.getApiService().indexTaskCount(userId, this, new TypeToken<ResultDO<IndexCount>>() {
                }.getType());
                ResultDO<List<IndexTask>> resultDO = (ResultDO<List<IndexTask>>) result;
                if (resultDO.getCode() == 0 && resultDO.getResult() != null) {
                    List<IndexTask> indexTasks = resultDO.getResult();
                    item.removeAllViews();
                    int j = 0;
                    if (indexTasks.size() != 0) {

                        for (IndexTask i : indexTasks) {
                            View v1 = LayoutInflater.from(mContext).inflate(R.layout.item_index_bottom, null);
                            TextView timeTitle = (TextView) v1.findViewById(R.id.time_title);
                            TextView time = (TextView) v1.findViewById(R.id.time);
                            ImageView img = (ImageView) v1.findViewById(R.id.img);
                            TextView title = (TextView) v1.findViewById(R.id.title);
                            TextView count = (TextView) v1.findViewById(R.id.count);
                            final int k = j;
                            v1.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (k == 0) {
                                        ((MainActivity) (getActivity())).setPageNo(1);
                                    }
                                }
                            });
                            timeTitle.setText(i.getWeek());
                            time.setText(i.getDoTime());
                            title.setText(i.getName());
                            count.setText(String.valueOf(i.getCount()));
                            if (j != 0) {
                                time.setTextColor(ContextCompat.getColor(mContext, R.color._808080));
                                timeTitle.setTextColor(ContextCompat.getColor(mContext, R.color._808080));
                                img.setImageResource(R.mipmap.connection_dark);
                            } else {
                                time.setTextColor(ContextCompat.getColor(mContext, R.color._63b1ff));
                                timeTitle.setTextColor(ContextCompat.getColor(mContext, R.color._63b1ff));
                                img.setImageResource(R.mipmap.connection_bright);
                            }
                            item.addView(v1);
                            j++;
                        }
                    }
                } else {
                    ToastUtils.showToast(mContext, resultDO.getMessage());
                }
                break;

            case Api.INDEX_TASK_COUNT:
                dissMissDialog();
                refreshLayout.setRefreshing(false);
                ResultDO<IndexCount> resultDO1 = (ResultDO<IndexCount>) result;
                if (resultDO1.getCode() == 0) {
                    final IndexCount indexCount = resultDO1.getResult();
                    noFinish.setText(String.valueOf(indexCount.getNoSucCount()));
                    finish.setText(String.valueOf(indexCount.getFinish()));
                    noSucCount.setText(String.valueOf(indexCount.getNoFinish()));
                    List<String> notices = new ArrayList<>();
                    for (int i = 0; i < indexCount.getList().size(); i++) {
                        notices.add(indexCount.getList().get(i).getTitle());
                    }
                    marqueeView.startWithList(notices);
                    marqueeView.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
                        @Override
                        public void onItemClick(int position, TextView textView) {
                            Intent intent = null;
                            intent = new Intent(mContext, WebViewActivity.class);
                            intent.putExtra("title","资讯详情");
                            intent.putExtra("url", ApiClient.URL + indexCount.getList().get(position).getId());
                            mContext.startActivity(intent);
                        }
                    });
                    List<Integer> list = new ArrayList<>();
                    list.add(indexCount.getReportCount());
                    list.add(indexCount.getNormalCount());
                    list.add(indexCount.getTempCount());
                    List<String> list1 = new ArrayList<>();
                    list1.add("居民反馈");
                    list1.add("常规巡检");
                    list1.add("分配巡检");
                    datas.clear();
                    for (int i = 0; i < 3; i++) {
                        PieData pieData = new PieData((int) list.get(i), mColors[i], list1.get(i));
                        datas.add(pieData);
                    }
                    pieNewChart.setDataList(datas);
                    pieNewChart.setmOnCenter(new HollowPieNewChart.OnCenterDraw() {
                        @Override
                        public void draw(Canvas canvas, Paint paint) {
                            paint.setColor(0xff333333);
                            paint.setTextSize(50);
                            String total = String.valueOf(indexCount.getTotalCount());
                            canvas.drawText(total, -paint.measureText(total) / 2, -PixUtils.dip2px(mContext, 4), paint);
                            paint.setColor(0xff808080);
                            paint.setTextSize(26);
                            String extraTotal = "总任务数";
                            canvas.drawText(extraTotal, -paint.measureText(extraTotal) / 2, PixUtils.dip2px(mContext, 12), paint);
                        }
                    });
                } else {
                    ToastUtils.showToast(mContext, resultDO1.getMessage() + "");
                }
                break;
            case Api.TASK_ID:
                ResultDO<Integer> resultDO2 = (ResultDO<Integer>) result;
                if (resultDO2.getCode() == 0) {
                    Intent intent = new Intent(mContext, TaskDetailActivity.class);
                    intent.putExtra("id", resultDO2.getResult());
                    startActivity(intent);
                } else {
                    ToastUtils.showToast(mContext, resultDO2.getMessage());
                }
                break;
        }

    }


    @Override
    public void onFailure() {
        refreshLayout.setRefreshing(false);
        dissMissDialog();
        ToastUtils.showToast(mContext, "服务器异常！");

    }

}
